package com.eightbears.beboy.ui.user.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.PostFormBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.Callback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.image.adapter.ImagePickerAdapter;
import com.eightbears.beboy.base.view.image.ui.ImageGridActivity;
import com.eightbears.beboy.base.view.image.ui.ImageViewDelActivity;
import com.eightbears.beboy.base.view.image.view.ImageItem;
import com.eightbears.beboy.base.view.image.view.ImagePicker;
import com.eightbears.beboy.base.view.viperpager.CirclePageIndicator;
import com.eightbears.beboy.entity.status.Status_Error;
import com.pnikosis.materialishprogress.ProgressWheel;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

import static com.eightbears.beboy.MainActivity.EVENT_VIP_CANCEL;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_FRIEND;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SENDPOST;
import static com.eightbears.beboy.ui.user.activity.ByVipActivity.EVENT_UPDATE_USER_STATUS;
import static com.eightbears.beboy.ui.user.activity.PostDetailActivity.EVENT_DELETE_POST;
import static com.eightbears.beboy.ui.user.activity.RepostPostActivity.EVENT_PARAMS_COMMENT;
import static com.eightbears.beboy.ui.user.activity.RepostPostActivity.EVENT_PARAMS_LIKE;
import static com.eightbears.beboy.ui.user.activity.RepostPostActivity.EVENT_PARAMS_REPOST;
import static com.eightbears.beboy.ui.user.activity.SettingActivity.EVENT_USER_HEAD_UPDATE;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_ADDRESS;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_CITY;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_DISTRICT;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_LATITUDE;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_LONGITUDE;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_PROVINCE;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.EVENT_PUBLISH_POST_SUCCESS;

/**
 * 发表朋友圈
 */
public class PublishFriendActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {

    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    public static final int REQUEST_CODE_LOCATION = 1;

    private PostFormBuilder builderPost = OkHttpUtils.post();
    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList;                  //当前选择的所有图片
    private int maxImgCount = 9;//允许选择图片最大数

    @BindView(R.id.view_loading)
    View view_loading;
    @BindView(R.id.et_content)
    EditText mEtContent;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.iv_biaoqing)
    ImageView mIvBiaoqing;
    @BindView(R.id.iv_publish_jinghao)
    ImageView mIvPublishJinghao;
    @BindView(R.id.ll_bottom)
    LinearLayout mLlBottom;
    @BindView(R.id.slv_view)
    ScrollView mSlvView;
    @BindView(R.id.vp_live_room_face)
    ViewPager mVpLiveRoomFace;
    @BindView(R.id.cpi_live_room_indicator)
    CirclePageIndicator mCpiLiveRoomIndicator;
    @BindView(R.id.progress_wheel)
    ProgressWheel mProgressWheel;
    @BindView(R.id.tv_loading_text)
    TextView mTvLoadingText;
    @BindView(R.id.ll_back)
    LinearLayout mLlBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.rl_title_root)
    RelativeLayout mRlTitleRoot;
    @BindView(R.id.tv_right_img_btn)
    TextView mTvRightImgBtn;
    @BindView(R.id.tv_submit)
    TextView mTvSubmit;
    @BindView(R.id.iv_right_icon)
    ImageView mIvRightIcon;
    @BindView(R.id.ll_right)
    LinearLayout mLlRight;
    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;
    @BindView(R.id.ws_finish)
    SwipeBackLayout mWs_finish;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_friend);
        ButterKnife.bind(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        mTvSubmit.setVisibility(View.VISIBLE);
        mTvSubmit.setText(getString(R.string.text_send));
        mTvTitle.setText(getString(R.string.text_edit_contents));
    }

    @Override
    protected void initData() {
        selImageList = new ArrayList<>();

        initAdapter();
    }

    @Override
    protected void initEvent() {
        mWs_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.tv_submit)
    void submit() {
        sendEdit();
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImageViewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                selImageList.addAll(images);
                adapter.setImages(selImageList);
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                selImageList.clear();
                selImageList.addAll(images);
                adapter.setImages(selImageList);
            }
        } else if (requestCode == REQUEST_CODE_LOCATION) {
            if (null == data) {
                ShowToast.showLongToast(getString(R.string.text_canceled));
                return;
            }

//            mLatitude = String.valueOf(data.getExtras().getDouble(PARAMS_LATITUDE));
//            mLongitude = String.valueOf(data.getExtras().getDouble(PARAMS_LONGITUDE));
//            mAddress = data.getExtras().getString(PARAMS_ADDRESS);
//            provinceId = data.getExtras().getString(PARAMS_PROVINCE);
//            districtId = data.getExtras().getString(PARAMS_DISTRICT);
//            cityId = data.getExtras().getString(PARAMS_CITY);
//            tv_publish_showlocation.setText(mAddress);
//            iv_publish_right.setVisibility(View.GONE);

        }
    }


    /**
     * 发送
     */
    private void sendEdit() {

        String content = mEtContent.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            ShowToast.showLongToast(R.string.alert_input_empty);
            return;
        }

        // 必填项
        builderPost.url(URL_FRIEND);
        builderPost.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        builderPost.addParams("content", content);

        for (int i = 0; i < selImageList.size(); i++) {
            builderPost.addFile("images[]", "images", new File(selImageList.get(i).path));
        }

        changeViewSend();//改变view的状态
        builderPost.build().execute(new Callback() {
            @Override
            public void onResponse(Object response) {
                ShowToast.showLongToast(R.string.text_post_success);
                EventBus.getDefault().post(EVENT_PUBLISH_POST_SUCCESS);//发消息通知已经发布成功
                selImageList.clear();
                finish();
            }

            @Override
            public Object parseNetworkResponse(Response response) throws Exception {
                return null;
            }

            @Override
            public void inProgress(float progress) {//发布的过程中进度监听
                super.inProgress(progress);
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                cancelSend();
                view_loading.setVisibility(View.GONE);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }

    /**
     * 发送，更改界面
     */
    private void changeViewSend() {
        view_loading.setVisibility(View.VISIBLE);//显示滚动圈
        mTvSubmit.setClickable(false);//禁止点击
        mTvSubmit.setEnabled(false);//不能点击
        mLlBack.setEnabled(false);//不能点击
        mTvSubmit.setBackgroundResource(R.drawable.bg_gray_style);//按钮变灰
//        btn_send.setText(R.string.text_post_posting);
        mLlBack.setClickable(false);//禁止回退
    }

    /**
     * 发送取消
     */
    private void cancelSend() {
        view_loading.setVisibility(View.GONE);//显示滚动圈
        mTvSubmit.setClickable(true);//禁止点击
        mTvSubmit.setEnabled(true);//不能点击
        mLlBack.setEnabled(true);//不能点击
        mTvSubmit.setBackgroundResource(R.drawable.background_circle_bead_blue_style);//按钮变灰
//        btn_send.setText(R.string.text_publish);
        mLlBack.setClickable(true);//禁止回退
    }


}
